package com.cn.txx.web.shiro;

import com.cn.txx.utils.Constants;
import com.cn.txx.utils.RedisUtils;
import org.apache.log4j.Logger;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;

import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * @program: ZyPrj
 * @Date: 2018/6/7 22:06
 * @Author: Mr.Deng
 * @Description:
 */
public class RedisSessionDao extends AbstractSessionDAO {
	@Autowired
	private RedisUtils redisUtils;

	public static final Logger LOGGER = Logger.getLogger(RedisSessionDao.class);

	/**
	 * 创建session
	 * @param session
	 * @return
	 */
	@Override
	protected Serializable doCreate(Session session) {
		Serializable sessionid = generateSessionId(session);
		assignSessionId(session,sessionid);
		saveSession(session);
		LOGGER.debug("新建session --->"+sessionid );
		return sessionid;
	}

	private void saveSession(Session session) {
		if(session != null && session.getId() != null){
			String sessdionid = getKey(session.getId().toString());
			redisUtils.set(sessdionid,session,(long)600);
		}
	}

	private String getKey(String s) {
		return Constants.SHIRO_SESSION_PREFIX+s;
	}

	@Override
	protected Session doReadSession(Serializable sessionId) {
		if(sessionId == null) {
			return null;
		}
		String key = getKey(sessionId.toString());
		Session session = (Session) redisUtils.get(key);
		return session;
	}

	@Override
	public void update(Session session) throws UnknownSessionException {
		saveSession(session);
	}

	@Override
	public void delete(Session session) {
		if(session == null || session.getId() == null) {
			return;
		}
		String key = getKey(session.getId().toString());
		redisUtils.remove(key);
	}

	@Override
	public Collection<Session> getActiveSessions() {
		Set<Serializable> keys = redisUtils.keys(Constants.SHIRO_SESSION_PREFIX);
		Set<Session> sessions = new HashSet<>();
		if(CollectionUtils.isEmpty(keys)) {
			return sessions;
		}
		for(Serializable key : keys) {
			Session session = (Session) redisUtils.get(key.toString());
			sessions.add(session);
		}
		return sessions;
	}
}
